package com.osmp.web.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;

/**
 * 鍖呭惈甯哥敤宸ュ叿鏂规硶
 *
 * @author
 * @version 1.0 2013-2-26
 */
public class Utils {

	private final static FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

	/**
	 * 鍒ゆ柇鏄惁涓虹┖
	 *
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return null == str || str.trim().length() == 0;
	}

	/**
	 * base64鍔犲瘑
	 *
	 * @param binaryData
	 * @return <code>String</code>
	 */
	public static String base64Encode(String str) {
		if (isEmpty(str)) {
			return "";
		}
		return (new sun.misc.BASE64Encoder()).encode(str.getBytes());
	}

	/**
	 * 鏁扮粍鐨凧oin鏂规硶
	 *
	 * @param obj
	 * @param sep
	 * @return
	 */
	public static String join(Object[] obj, String sep) {
		if (obj == null) {
			return null;
		}

		final int length = obj.length;
		if (length == 0) {
			return "";
		}
		final StringBuilder sb = new StringBuilder().append(obj[0]);

		for (int i = 1; i < length; i++) {
			sb.append(sep).append(obj[i]);
		}

		return sb.toString();
	}

	/**
	 * 鎶婂瓧绗︿覆杞崲鎴恉ouble 濡傛灉涓�娆¤繑鍥瀌efValue
	 *
	 * @param value
	 * @param defValue
	 * @return
	 */
	public static double stringToDouble(String value, double defValue) {

		try {
			return Double.parseDouble(value);
		} catch (final NumberFormatException e) {
			return defValue;
		}

	}

	/**
	 * 瀛楃涓茶浆鎹负long
	 *
	 * @param val
	 * @param defVal
	 *            濡傛灉杞崲澶辫触缁欏畾鐨勯粯璁ゅ��
	 * @return
	 */
	public static long parseLong(String val, long defVal) {
		try {
			return Long.parseLong(val);
		} catch (final Exception e) {
			return defVal;
		}
	}

	/**
	 * 灏嗗瓧绗︿覆杞崲鎴愭棩鏈熸牸寮�
	 *
	 * @param pattern
	 * @param date
	 * @return 杞崲澶辫触鏃惰繑鍥瀗ull
	 */
	public static Date stringToDate(String pattern, String date) {
		try {
			return new SimpleDateFormat(pattern).parse(date);
		} catch (final Exception e) {
			return null;
		}
	}

	/*****
	 * 灏嗘绉掕浆鎹㈡垚鏃ユ湡鏍煎紡鐨勫瓧绗︿覆
	 *
	 * @param millis
	 * @return
	 */
	public static String longTodateString(long millis) {
		return FAST_DATE_FORMAT.format(millis);
	}

	/**
	 * 杞崲棣栧瓧姣嶅ぇ鍐�
	 *
	 * @param str
	 * @return
	 */
	public static String firstUpper(String str) {
		final String s = (str.charAt(0) + "").toUpperCase();
		return s + str.substring(1);
	}

	/**
	 * 鎶婃椂闂磋浆鎹㈡垚yyyy-MM-dd HH:mm:ss 鏍煎紡
	 *
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date) {
		if (date == null) {
			return null;
		}
		return FAST_DATE_FORMAT.format(date);
	}

	/**
	 * 鎶婃椂闂磋浆鎹㈡垚yyyy骞碝M鏈坉d鏃H鏃秏m鍒唖s绉� 鏍煎紡
	 *
	 * @param date
	 * @return
	 */
	public static String dateToZhString(Date date) {
		if (date == null) {
			return null;
		}
		return new SimpleDateFormat("yyyy骞碝M鏈坉d鏃H鏃秏m鍒唖s绉�").format(date);
	}

	/****
	 * 灏嗘椂闂磋浆鎹㈡垚鏃堕棿鎴虫牸寮�
	 *
	 * @param date
	 * @return
	 */
	public static String dateToTimeStamp(Date date) {
		if (date != null) {
			return new SimpleDateFormat("yyyyMMddHHmmss").format(date);
		}

		return null;
	}

	/******
	 * 灏嗘棩鏈熸牸寮�2013-10-11T10:28:50.442382杞崲鎴愭棩鏈熷搴旀绉掓暟瀛楃涓�
	 *
	 * @return
	 */
	public static String stringtodate(String date) {
		if (date == null || date.length() == 0) {
			return null;
		}
		final String pattern = "\\d{4}-\\d{2}-\\d{2}[a-zA-Z\\s]+\\d{2}:\\d{2}:\\d{2}.\\d*";
		final StringBuffer sbf = new StringBuffer();
		if (date.matches(pattern)) {
			for (final String s : StringUtils.substringBefore(date, ".").split("[a-zA-Z\\s]+")) {
				sbf.append(s + " ");
			}
			return String.valueOf(stringToDate("yyyy-MM-dd hh:mm:ss", sbf.toString().trim()).getTime());
		} else {
			return date;
		}
	}

	/**
	 * 鏍煎紡鍖杕ac鍦板潃鎸夋病涓や綅鍒嗗壊
	 *
	 * @param mac
	 *            闇�瑕佹牸寮忓寲鐨刴ac鍦板潃
	 * @param sep
	 *            鍒嗛殧绗� ":"鎴栬��" "绛�
	 * @return
	 */
	public static String formatMac(String mac, String sep) {
		if (Assert.isEmpty(mac)) {
			return "";
		}

		mac = mac.replaceAll("[^a-zA-Z0-9]", "");

		final StringBuilder sb = new StringBuilder();

		for (int i = 0; i < mac.length(); i += 2) {
			sb.append(mac.substring(i, i + 2) + sep);
		}

		return sb.substring(0, sb.length() - sep.length());

	}

	/**
	 * 杩斿洖寮傚父鐨勫瓧绗︿覆
	 *
	 * @param e
	 * @return
	 */
	public static String exceptionToString(Exception e) {
		String str = "";
		if (e != null) {
			final StringWriter sw = new StringWriter();
			final PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			str = sw.toString();
			pw.close();
			try {
				sw.close();
			} catch (final IOException e1) {
				e1.printStackTrace();
			}
		}

		return str;
	}

	/**
	 * 濡傛灉瀛楃涓蹭负绌哄垯杩斿洖def鍚﹀垯杩斿洖str
	 *
	 * @param str
	 * @param def
	 * @return
	 */
	public static String nullToDefault(String str, String def) {
		return Assert.isEmpty(str) ? def : str;
	}

	/**
	 * 灏嗘绉掓暟鎹㈢畻鎴恱澶﹛鏃秞鍒唜绉抶姣
	 *
	 * @param ms
	 * @return
	 */
	public static String millisToTime(long ms) {
		final int ss = 1000;
		final int mi = ss * 60;
		final int hh = mi * 60;
		final int dd = hh * 24;

		final long day = ms / dd;
		final long hour = (ms - day * dd) / hh;
		final long minute = (ms - day * dd - hour * hh) / mi;
		final long second = (ms - day * dd - hour * hh - minute * mi) / ss;
		final long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

		final StringBuffer sb = new StringBuffer("");
		if (day != 0l) {
			sb.append(day + "澶�");
		}
		if (hour != 0l) {
			sb.append(hour + "灏忔椂");
		}
		if (minute != 0l) {
			sb.append(minute + "鍒�");
		}

		if (milliSecond != 0l) {
			sb.append(second + "." + milliSecond + "绉�");
		} else {
			sb.append(second + "绉�");
		}
		return sb.toString();
	}

	/**
	 * 瀛楃涓瞭rim鎿嶄綔
	 *
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		return str != null ? str.trim() : null;
	}

	/**
	 * 瀛楃涓瞭rim鎿嶄綔
	 *
	 * @param str
	 * @return
	 */

	/******
	 * base64瑙ｇ爜 杩斿洖瑙ｇ爜鍚庣殑瀛楃涓�
	 *
	 * @param str
	 *            base64缂栫爜鍚庣殑瀛楃涓�
	 * @return
	 */
	public static String decodeBase64(String str) {
		if (str == null || str.length() == 0) {
			return "";
		} else {
			final Base64 base64 = new Base64();
			try {
				final byte[] debytes = base64.decode(str);
				return new String(debytes);
			} catch (final Exception e) {
				e.printStackTrace();
				return "";
			}
		}
	}

	public static String sqlParaFormat(String str) {
		return str != null ? str.replaceAll("'", "''") : null;
	}

	public static String covertToUTF8(String str) {
		if (str == null) {
			return str;
		}
		try {
			return new String(str.getBytes("ISO-8859-1"), "UTF-8");
		} catch (final UnsupportedEncodingException e) {
		}
		return str;
	}

	public static String covertToGBK(String str) {
		if (str == null) {
			return str;
		}
		try {
			return new String(str.getBytes("ISO-8859-1"), "GBK");
		} catch (final UnsupportedEncodingException e) {
		}
		return str;
	}

	

	public static String getRemoteHost(javax.servlet.http.HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");  
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
            ipAddress = request.getHeader("Proxy-Client-IP");  
        }  
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
            ipAddress = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
            ipAddress = request.getRemoteAddr();  
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                //鏍规嵁缃戝崱鍙栨湰鏈洪厤缃殑IP  
                InetAddress inet=null;  
                try {  
                    inet = InetAddress.getLocalHost();  
                } catch (UnknownHostException e) {  
                    e.printStackTrace();  
                }  
                ipAddress= inet.getHostAddress();  
            }  
        }  
        //瀵逛簬閫氳繃澶氫釜浠ｇ悊鐨勬儏鍐碉紝绗竴涓狪P涓哄鎴风鐪熷疄IP,澶氫釜IP鎸夌収','鍒嗗壊  
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
            if(ipAddress.indexOf(",")>0){  
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
            }  
        }  
        return ipAddress;
	}


	public static <T> boolean contains(final T[] array, final T v) {
		for (final T e : array)
			if (e == v || v != null && v.equals(e))
				return true;
		return false;
	}
}
